package com.jwb.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Clob;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import javax.activation.MimetypesFileTypeMap;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Slf4j
public class ToolsUtil {


	/**
	 * mysql因为没有递归sql,编写模板递归sql达到同等效果
	 */

	public static String nestSql(String paraSql,String tableSql,String curId,Boolean content)
	{
		String enter="\n";
		String sql="";
		sql="SELECT "+paraSql+enter+
				"		FROM ("+enter+
				"			 SELECT"+enter+
				"			 NAME,"+enter+
				"			 id,"+enter+
				"			 pid,"+enter+
				"			 @le:= IF (pid = -1 ,0,IF( LOCATE( CONCAT('|',pid,':'),@pathlevel) > 0,SUBSTRING_INDEX( SUBSTRING_INDEX(@pathlevel,CONCAT('|',pid,':'),-1),'|',1) +1,@le+1) ) levels,"+enter+
				"			 @pathlevel:= CONCAT(@pathlevel,'|',id,':', @le ,'|') pathlevel,"+enter+
				"			 @pathnodes:= IF( pid =-1,',root', CONCAT_WS(',',IF( LOCATE( CONCAT('|',pid,':'),@pathall) > 0 ,SUBSTRING_INDEX( SUBSTRING_INDEX(@pathall,CONCAT('|',pid,':'),-1),'|',1),@pathnodes ) ,pid ) )paths,"+enter+
				"			 @pathall:=CONCAT(@pathall,'|',id,':', @pathnodes ,'|') pathall"+ enter+
				"			FROM (tableSql) t , "+enter+
				"			("+enter+
				"			 SELECT "+enter+
				"			 @le:=0,"+enter+
				"			 @pathlevel:='', "+enter+
				"			 @pathall:='',"+enter+
				"			 @pathnodes:=''"+enter+
				"			)  vv"+enter+
				"			ORDER BY pid,id"+enter+
				"		) src"+enter;
		if (content){
			sql+="		WHERE (instr(CONCAT( paths, ',' ),',"+curId+",')>0 OR id = '"+curId+"' ) "+enter+
					"		ORDER BY pid";
		}else{
			sql+="		WHERE instr(CONCAT( paths, ',' ),',"+curId+",')>0 "+enter+
					"		ORDER BY pid";
		}

		sql=sql.replaceAll("tableSql", tableSql);

		return sql;
	}

	/**
	 * 部门属sql
	 * @param curId
	 * @param content
	 * @return
	 */
	public static String nestDeptSql(String curId,Boolean content)
	{
		String sql="";
		String paraSql="id";
		String tableSql="SELECT dept_name AS NAME,dept_id AS id, dept_parent_id AS pid FROM dept  WHERE dept_sts='A' ";
		sql=ToolsUtil.nestSql(paraSql, tableSql, curId, true);
		return sql;
	}

	/**
	 * null或"null"转空串
	 * @param str
	 * @return
	 */
	public static String nullToStr(String str) {
		String chn = "";
		try {
			if ("null".equals(str) || str == null) {
				chn = "";
			} else {
				chn = str;
				//chn = chn.replaceAll("\\{", "");
			}
		} catch (Exception e) {

		}
		return chn;
	}

	/**
	 * reader转字符串
	 * @param reader
	 * @return
	 */
	public static String read(Reader reader) {
		String sb = "";
		try {
			int s;

			while ((s = reader.read()) != -1) {
				sb += (char) s;
			}
			// reader.close();
		} catch (Exception e) {

		}
		return sb;
	}

	/**
	 * uuid32
	 * @return
	 */
	public static String get32bituuid()
	{
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 根据文件名读取属性值
	 * @param fileName
	 * @param prop
	 * @return
	 * @throws Exception
	 */
	public static String getProp(String fileName,String prop) {
		String result="";
		try
		{
			Properties p = new Properties();
			ClassPathResource classPathResource = new ClassPathResource("/prop/"+fileName);
			InputStream in = classPathResource.getInputStream();
			p.load(in);
			result = p.getProperty(prop);
			in.close();
		}
		catch(Exception e)
		{

		}
		return result;

	}


	public static String[] getProp(String fileName,String...props){
		String[] strs = new String[props.length];
		Properties p = new Properties();
		try(InputStream in = new ClassPathResource("/prop/"+fileName).getInputStream()){
			p.load(in);
			int idx = 0;
			for(String prop:props){
				strs[idx] = p.getProperty(prop);
				idx++;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return strs;
	}

	/**
	 * 字符串decode
	 * @param str
	 * @return
	 */
	public static String decode(String str)
	{
		try
		{
			if (null==str){
				return null;
			}else{
				return URLDecoder.decode(str, "utf-8");
			}
		}
		catch (UnsupportedEncodingException e)
		{
			return null;
		}
	}

	/**
	 * 重复字符串拼接
	 * @param str
	 * @param n
	 * @return
	 */
	public static String repeatString(String str, int n) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < n; i++) {
			sb.append(str+",");
		}
		return sb.toString();
	}

	/**
	 * 文件删除
	 * @param file
	 */

	public static void deleteFile(File file){
		//判断文件不为null或文件目录存在
		if (file == null || !file.exists()){
			System.out.println("文件删除失败,请检查文件路径是否正确");
			return;
		}
		//取得这个目录下的所有子文件对象
		File[] files = file.listFiles();
		//遍历该目录下的文件对象
		for (File f: files){
			//打印文件名

			//判断子目录是否存在子目录,如果是文件则删除
			if (f.isDirectory()){
				deleteFile(f);
			}else {
				System.out.println(f.getName()+"---已删除");
				f.delete();

			}
		}
		//删除空文件夹  for循环已经把上一层节点的目录清空。
		file.delete();
	}
	/**
	 * 文件crc32校验码
	 * @param file
	 * @return
	 */
	public static String getFileCRCCode(File file)
	{
		FileInputStream fileinputstream;
		CRC32 crc32 = new CRC32();
		try {
			fileinputstream = new FileInputStream(file);

			for (CheckedInputStream checkedinputstream =
				 new CheckedInputStream(fileinputstream, crc32);
				 checkedinputstream.read() != -1;
			) {
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String result = Long.toHexString(crc32.getValue());
		if(result.length()<8){
			for(int i=0;i<8-result.length();i++){
				result="0"+result;
			}
		}
		return result;
//       return Long.toHexString(crc32.getValue());
	}

	/**
	 * 将文件转字节流
	 * @param file
	 * @return
	 */
	public static byte[] fileConvertToByteArray(File file) {

		byte[] data = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			int len;
			byte[] buffer = new byte[1024];
			while ((len = fis.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}

			data = baos.toByteArray();

			fis.close();
			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return data;
	}

	/**
	 *视频封面截取
	 */
	public  static JSONObject processImg(JSONObject paraData){

		JSONObject jsoResp= new JSONObject();
		jsoResp.put("respCode", "-1");
		jsoResp.put("respDesc", "转换异常");
		String imgId=ToolsUtil.get32bituuid();
		String videoPath=!paraData.containsKey("filePath") ? "" : paraData.getString("filePath");
		String ffmpegPath=!paraData.containsKey("ffmpegPath") ? "" : paraData.getString("ffmpegPath");
		String imgPath=!paraData.containsKey("imgPath") ? "" : paraData.getString("imgPath");
		File file = new File(videoPath);
		if (!file.exists()) {
			jsoResp.put("respCode", "-1");
			jsoResp.put("respDesc", "路径[" + videoPath + "]对应的视频文件不存在!");
			return jsoResp;
		}
		file = new File(ffmpegPath);
		if (!file.exists()) {
			jsoResp.put("respCode", "-1");
			jsoResp.put("respDesc", "路径[" + ffmpegPath + "]对应的ffmpeg不存在!");
			return jsoResp;
		}
		File dir = new File(imgPath);
		if(!dir.exists())
			dir.mkdirs();
		List<String> commands = new ArrayList<String>();
		commands.add(ffmpegPath);
		commands.add("-i");
		commands.add(videoPath);
		commands.add("-y");
		commands.add("-f");
		commands.add("image2");
		commands.add("-ss");
		commands.add("1");//这个参数是设置截取视频多少秒时的画面
		//commands.add("-t");
		//commands.add("0.001");
		commands.add("-s");
		commands.add("300*300");
		commands.add(imgPath+"\\"+imgId+".png");
		try {
			ProcessBuilder builder = new ProcessBuilder();
			builder.redirectErrorStream(true);
			builder.command(commands);
			Process proc = builder.start();
			consumeInputStream(proc.getInputStream());
			consumeInputStream(proc.getErrorStream());
			int exit = proc.waitFor();
			if(exit==0||exit==1){
				jsoResp.put("respCode", "0");
				jsoResp.put("respDesc", "封面截取成功");
				jsoResp.put("imgPath", imgPath+"\\"+imgId+".png");
			}else{
				jsoResp.put("respCode", "-1");
				jsoResp.put("respDesc", "封面截取失败");
			}
			return jsoResp;
		} catch (Exception e) {
			e.printStackTrace();
			jsoResp.put("respCode", "-1");
			jsoResp.put("respDesc", "封面截取失败");
		}

		return jsoResp;
	}

	/**
	 * @return	消费输入流, 防止线程阻塞
	 */
	private static String consumeInputStream(InputStream is){
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String s ;
		StringBuilder sb = new StringBuilder();
		try{
			while((s=br.readLine())!=null){
				System.out.println(s);
				sb.append(s);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return sb.toString();
	}


	/**
	 * 取得当前时间戳（精确到秒）
	 *
	 * @return nowTimeStamp
	 */
	public static String getNowTimeStamp() {
		long time = System.currentTimeMillis();
		String nowTimeStamp = String.valueOf(time / 1000);
		return nowTimeStamp;
	}


	/**
	 * 日期格式字符串转换成时间戳
	 *
	 * @param dateStr
	 *            字符串日期
	 * @param format
	 *            如：yyyy-MM-dd HH:mm:ss
	 *
	 * @return
	 */
	public static String Date2TimeStamp(String dateStr, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}




	/**
	 * Java将Unix时间戳转换成指定格式日期字符串
	 *
	 * @param timestampString
	 *            时间戳 如："1473048265";
	 * @param formats
	 *            要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
	 *
	 * @return 返回结果 如："2016-09-05 16:06:42";
	 */
	public static String TimeStamp2Date(String timestampString, String formats) {
		if (TextUtils.isEmpty(formats))
			formats = "yyyy-MM-dd HH:mm:ss";
		Long timestamp = Long.parseLong(timestampString) * 1000;
		String date = new SimpleDateFormat(formats, Locale.CHINA)
				.format(new Date(timestamp));
		return date;
	}



	/**
	 * 两日期相减相差分钟数
	 *
	 * @return
	 */
	public static long getMinuteForDateCompare(java.util.Date date1,
											   java.util.Date date2) {

		long i = (date2.getTime() - date1.getTime()) / (1000 * 60);
		return i;
	}

	/**
	 * 字符串时间转sql date时间
	 * yyyy-MM-dd HH:mm:ss
	 * @param dateStr
	 * @param formats
	 * @return
	 */
	public static java.sql.Date dateStrToSqlDate(String dateStr, String formats) {
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		java.sql.Date sqlDate=null;
		/** yyyy-MM-dd为字符串的格式 **/
		/** 要转化为java.util.Date的字符串 **/
		try {
			java.util.Date date = sdf.parse(dateStr);
			sqlDate = new java.sql.Date(date.getTime());
			//System.out.println(sqlDate.getTime());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return sqlDate;
	}


	/**
	 * sqlDate时间转字符串时间
	 * @param sqlDate
	 * @param formats yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String  sqlDateToDateStr(java.sql.Date sqlDate, String formats) {
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		java.util.Date d = new java.util.Date(sqlDate.getTime());
		return sdf.format(d);
	}


	/**
	 * 获得当前sqlDate时间
	 * @param formats yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public  static java.sql.Date sqlCurrentDate(String formats) {
		java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

		return date;
	}




	/**
	 * 字符串时间 转utilDate时间
	 * @param dateStr
	 * @param formats
	 * @return
	 */
	public static java.util.Date dateStrToUtilDate(String dateStr, String formats) {
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		java.util.Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
		}
		return date;
	}


	/**
	 * utilDate时间转字符串时间
	 * @param utilDate
	 * @param formats
	 * @return
	 */
	public static String  utilDateToDateStr(java.util.Date utilDate, String formats) {
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		return sdf.format(utilDate);
	}

	/**
	 * 将当前时间转成utilDate时间
	 * @param formats
	 * @return
	 */
	public  static String  utilDateCurrentToDateStr(String formats) {
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		java.util.Date date = new java.util.Date();
		return sdf.format(date);
	}


	/**
	 * utilDate转sqlDate时间
	 * @param utilDate
	 * @return
	 */
	public  static java.sql.Date utilDateToSqlDate(java.util.Date utilDate)
	{
		java.sql.Date date = new java.sql.Date(utilDate.getTime());

		return date;
	}



	/**sqlDate转utilDate时间
	 * sqlDate转utilDate时间
	 * @param sqlDate
	 * @return
	 */
	public  static java.util.Date sqlDateToUtilDate(java.sql.Date sqlDate)
	{
		java.util.Date date = new java.util.Date(sqlDate.getTime());

		return date;
	}


	public static Timestamp currentDateToTimestamp(){
		Timestamp time = new Timestamp(new java.util.Date().getTime());
		return time;
	}

	public static Timestamp dateStrToTimestamp(String dateStr, String formats){
		Timestamp time = null;
		SimpleDateFormat sdf = new SimpleDateFormat(formats);
		try {
			java.util.Date date = sdf.parse(dateStr);
			time = new Timestamp(date.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return time;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		//创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		//每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		//使用一个输入流从buffer里把数据读取出来
		while( (len=inStream.read(buffer)) != -1 ){
			//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		//关闭输入流
		inStream.close();
		//把outStream里的数据写入内存
		return outStream.toByteArray();
	}


	public static String readStringFromClob(Clob clobField) // 类型转换方法
			throws Exception {
		Reader in = null;
		in = clobField.getCharacterStream();
		int length = 0;
		char buffer[] = new char[1024];
		StringBuffer sb = new StringBuffer();
		try {
			while ((length = in.read(buffer)) != -1)
				sb.append(buffer, 0, length);
		} catch (Exception e) {
			throw new Exception("IO error:".concat(String.valueOf(String.valueOf(e.getMessage()))));
		} finally {
			in.close();
		}
		return sb.toString();
	}



	public static boolean isPic(String imgUrl){
		boolean result = false;
		String url = imgUrl.toLowerCase().trim();
		String[] exts = new String[]{".bmp",".jpg",".jpeg",".gif",".png",".tif",".tiff",".tga",".psd"};
		for(String e:exts){
			if(url.indexOf(e)>-1){
				result = true;
				break;
			}
		}
		return result;
	}


	public static String correctPicExt(String imgUrl){
		String url = imgUrl.toLowerCase().trim();
		String[] exts = new String[]{".bmp",".jpg",".jpeg",".gif",".png",".tif",".tiff",".tga",".psd",".mp4"};
		for(String e:exts){
			if(url.endsWith(e)){
				return url;
			}else if(url.indexOf(e)>-1){
				url=url.substring(0,url.indexOf(e)+e.length());
				break;
			}
		}
		return url;
	}




	public static String getPicMimeType(String ext){
		String mType = "";
		switch(ext){
			case ".bmp":
				mType = "image/x-ms-bmp";
				break;
			case ".jpg":
				mType = "image/jpeg";
				break;
			case ".jpeg":
				mType="image/jpeg";
				break;
			case ".gif":
				mType="image/gif";
				break;
			case ".png":
				mType="image/png";
				break;
			case ".tif":
				mType="image/tiff";
				break;
			case ".tiff":
				mType="image/tiff";
				break;
			case ".tga":
				mType="image/x-targa";
				break;
			case ".psd":
				mType="image/vnd.adobe.photoshop";
				break;
			default:
				break;
		}

		return mType;
	}



	public static boolean hasFileProtocol(String path){
		boolean result = false;
		String[] pts = new String[]{"http","https","ftp"};
		for(String p:pts){
			if(path.toLowerCase().startsWith(p)){
				result = true;
				break;
			}
		}

		return result;
	}
	/**
	 *
	 * 根据图片地址url 下载到指定路径
	 * */
	public static boolean downloadPicture(String urlList,String savePath) {
		URL url = null;
		boolean resultFlag=false;
		try {
			url = new URL(urlList);
			File f = new File(savePath);

			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			byte[] context=output.toByteArray();
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
			resultFlag=true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return resultFlag;
	}

	/**
	 *
	 * 根据图片地址url 下载到指定路径
	 * */
	public static boolean downloadPic(String urlList,String savePath){

		boolean resultFlag=false;
		try
		{
			URL url = new URL(urlList);
			//打开链接
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			//设置请求方式为"GET"
			conn.setRequestMethod("GET");
			//超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			//通过输入流获取图片数据
			InputStream inStream = conn.getInputStream();
			//得到图片的二进制数据，以二进制封装得到数据，具有通用性
			byte[] data = readInputStream(inStream);
			//new一个文件对象用来保存图片，默认保存当前工程根目录
			File imageFile = new File(savePath);
			//创建输出流
			FileOutputStream outStream = new FileOutputStream(imageFile);
			//写入数据
			outStream.write(data);
			//关闭输出流
			outStream.close();
			resultFlag=true;
		}
		catch(Exception e)
		{

		}
		return resultFlag;
	}

	/**
	 * 文件下载到指定路径
	 * @param paraData
	 * @return
	 */
	public static String getDownLoadFilePath(JSONObject paraData)
	{
		String filePath="";
		String rootPath =paraData.containsKey("rootPath")?paraData.getString("rootPath"):"D:\\";
		String floder = paraData.containsKey("floder")?paraData.getString("floder"):"file/other";
		String fileid = paraData.containsKey("fileid")?paraData.getString("fileid"):"";
		File dir = new File(rootPath+floder);
		if(!dir.exists())
			dir.mkdirs();
		System.out.println("rootPath+floder----"+rootPath+floder);
		String url=paraData.containsKey("url")?paraData.getString("url"):"";
		String name="";
		try
		{
			name =ToolsUtil.correctPicExt(url.substring(url.lastIndexOf("/")+1));
		}
		catch(Exception e)
		{

		}
		if("".equals(name))
		{
			name=ToolsUtil.get32bituuid();
		}


		if(!"".equals(fileid))
		{
			name=fileid;
		}

		String savePath=rootPath+floder+"/"+name;
		savePath=savePath.replace("?", "");
		boolean flag=ToolsUtil.downloadPic(url, savePath);
		System.out.println("文件生成("+savePath+")----"+(flag?"成功":"失败"));
		if(flag)
		{
			filePath=savePath;
		}

		return filePath;
	}

	/**
	 * 根据url 获取html源码
	 *
	 */
	public static JSONObject getHtml(String url) {
		CloseableHttpClient httpClient = null;

		try {
			System.out.println("getHttps():" + url);
			HttpGet get = new HttpGet(url);
			httpClient = HttpClients.custom().build();

			CloseableHttpResponse response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				String respStr = EntityUtils.toString(entity, Consts.UTF_8);
				get.releaseConnection();
				JSONObject object = new JSONObject();
				object.put("respBody", respStr);
				return object;
			} else {
				System.out.println("getHttps():get请求失败，请求URL:" + url);

				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static JSONObject getHttps(String url, Map<String, String> headers){
		JSONObject jsonObject = null;
		CloseableHttpClient client = null;
		String absUrl=url;
		CloseableHttpResponse response = null;
		try{
			client = HttpClients.createDefault();
			URIBuilder uriBuilder = new URIBuilder(url);
//      	uriBuilder.addParameters(nameValuePairList);
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
			httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
			if (headers!=null){
				for(String h:headers.keySet()){
					httpGet.setHeader(h,headers.get(h));
				}
			}

			HttpClientContext context = HttpClientContext.create();
//          response = client.execute(httpGet);
			response = client.execute(httpGet,context);
			HttpHost target = context.getTargetHost();
			List<URI> redirectLocations = context.getRedirectLocations();
			URI location = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
			absUrl = location.toASCIIString();

			int statusCode = response.getStatusLine().getStatusCode();

			if (200 == statusCode){

				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity,"UTF-8");
				if(!absUrl.equals(url))
				{
					jsonObject = new JSONObject();
					jsonObject.put("respCode", "0");
					try
					{
						jsonObject = JSONObject.parseObject(result);
					}
					catch(Exception e)
					{
						jsonObject.put("result", result);
					}
					jsonObject.put("location", absUrl);
					return jsonObject;
				}
				try{
					jsonObject = new JSONObject();
					try
					{
						jsonObject = JSONObject.parseObject(result);
					}
					catch(Exception e)
					{
						jsonObject.put("result", result);
					}

					jsonObject.put("respCode", "0");
					return jsonObject;
				}catch (Exception e){
					jsonObject = new JSONObject();
					jsonObject.put("respCode", "-1");
					jsonObject.put("result", result);
					return jsonObject;
				}
			}
			else if(403 == statusCode)
			{
				jsonObject = new JSONObject();
				jsonObject.put("respCode", "-1");
				jsonObject.put("location", absUrl);
				return jsonObject;
			}
			else{
				log.error("HttpClientService-line: {}, errorMsg{}"+"GET请求失败！");

			}
		}catch (Exception e){
			log.error("HttpClientService-line: {}, Exception: {}"+e);
		} finally {
			try {
				response.close();
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return null;
	}

	/**
	 * description：发送HTTPS Get请求
	 *
	 * @param url
	 * @return
	 */
//	public static JSONObject getHttps(String url) {
//		CloseableHttpClient httpClient = null;
//
//		try {
//			System.out.println("getHttps():" + url);
//			HttpGet get = new HttpGet(url);
//			httpClient = HttpClients.custom().build();
//
//			CloseableHttpResponse response = httpClient.execute(get);
//			HttpEntity entity = response.getEntity();
//			StatusLine statusLine = response.getStatusLine();
//
//			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
//				String respStr = EntityUtils.toString(entity, Consts.UTF_8);
//				get.releaseConnection();
//				System.out.println("getHttps():" + respStr);
//
//				JSONObject object = JSONObject.fromObject(respStr);
//				return object;
//			} else {
//				System.out.println("getHttps():get请求失败，请求URL:" + url);
//
//				return null;
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		} finally {
//			try {
//				httpClient.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}





	public static JSONObject postHttps(String url, String jsonStr) {
		try {

			System.out.println("postHttps():" + url);
			HttpPost post = new HttpPost(url);
			if (jsonStr != null) {
				post.setEntity(new StringEntity(jsonStr, Consts.UTF_8));
			}

			CloseableHttpClient httpClient = HttpClients.custom().build();

			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String entitystr = EntityUtils.toString(entity, Consts.UTF_8);
			httpClient.close();
			post.releaseConnection();

			JSONObject object = JSONObject.parseObject(entitystr);
			System.out.println("postHttps():" + object.toString());

			return object;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static String postHttpsStr(String url, String str) {
		try {

			System.out.println("postHttps():" + url);
			HttpPost post = new HttpPost(url);
			if (str != null) {
				post.setEntity(new StringEntity(str, Consts.UTF_8));
			}

			CloseableHttpClient httpClient = HttpClients.custom().build();

			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String entitystr = EntityUtils.toString(entity, Consts.UTF_8);
			httpClient.close();
			post.releaseConnection();

			//JSONObject object = JSONObject.parseObject(entitystr);
			System.out.println("postHttps():" + entitystr);

			return entitystr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}



	public static JSONObject postHttps(String url, String jsonStr, Map<String, String> headers) {
		try {
			log.info("postHttps():" + url);
			HttpPost post = new HttpPost(url);
			if (StringUtils.hasLength(jsonStr)) {
				post.setEntity(new StringEntity(jsonStr, Consts.UTF_8));
				log.info("postHttps():" + jsonStr);
			}

			// 增加header信息
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}

			CloseableHttpClient httpClient = HttpClients.custom().build();

			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String entitystr = EntityUtils.toString(entity, Consts.UTF_8);
			httpClient.close();
			post.releaseConnection();

			JSONObject object = JSONObject.parseObject(entitystr);

			log.info("postHttps():" + object.toString());

			return object;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("postHttps():发送HTTPS请求时异常", e);
			return null;
		}

	}

	public static JSONObject postHttps(String url, String jsonStr, Map<String, String> headers,BasicCookieStore cookieStore) {
		try {
			log.info("postHttps():" + url);
			HttpPost post = new HttpPost(url);
			if (StringUtils.hasLength(jsonStr)) {
				post.setEntity(new StringEntity(jsonStr, Consts.UTF_8));
				log.info("postHttps():" + jsonStr);
			}

			// 增加header信息
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}


			CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String entitystr = EntityUtils.toString(entity, Consts.UTF_8);
			httpClient.close();
			post.releaseConnection();

			JSONObject object = JSONObject.parseObject(entitystr);

			log.info("postHttps():" + object.toString());

			return object;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("postHttps():发送HTTPS请求时异常", e);
			return null;
		}

	}



	/**
	 * 根据图片url地址将图片上传到图床服务器
	 *
	 */
	public static JSONObject uploadNetImgFile( URI uri,String postUrl,Map<String, String> headers,JSONObject paraData ) {
		try {
			CloseableHttpClient httpClient = HttpClients.custom().build();
			HttpEntity entity = httpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
			HttpPost httpPost = new HttpPost(postUrl);
			// 增加header信息
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpPost.addHeader(entry.getKey(), entry.getValue());
				}
			}

			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

			String filename = FilenameUtils.getName(uri.toString());
			String contentType = ContentType.get(entity).getMimeType();

			if (filename.indexOf(".") < 0) {
				filename = filename.concat(FileExtensionUtil.getExtensionByContentType(contentType));
				//filename=filename+".png";
			}
			log.info("uploadNetImgFile():contenttype=" + contentType);
			log.info("uploadNetImgFile():name=" + filename);
			String name="file";
			if(paraData.containsKey("name"))
			{
				name=paraData.getString("name");
			}

			multipartEntityBuilder.addBinaryBody(name, EntityUtils.toByteArray(entity), ContentType.get(entity),
					filename);

			httpPost.setEntity(multipartEntityBuilder.build());

			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity rentity = response.getEntity();

			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				String entityStr = EntityUtils.toString(rentity, Consts.UTF_8);
				log.info("uploadNetImgFile():entityStr = " + entityStr);

				JSONObject entityjson = JSONObject.parseObject(entityStr);
				System.out.println(entityjson.toString());

				if (entityjson.containsKey("errcode")) {
					//entityjson.replace("errmsg", WeiXinError.getDesc(entityjson.getString("errcode")));
				}

				return entityjson;
			}


		} catch (Exception e) {
			log.error("uploadNetImgFile():上传图文消息内的图片获取URL时发生异常", e);
		}
		return null;
	}




	/**
	 * 根据本地图片上传到图床服务器
	 *
	 */
	public static JSONObject uploadLocalImgFile(String filePath,String postUrl,Map<String, String> headers,JSONObject paraData ) {
		try {

			CloseableHttpClient httpClient = HttpClients.custom().build();
//			HttpEntity entity = httpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
//			postUrl="https://mp.toutiao.com/mp/agw/article_material/photo/upload_picture?type=ueditor&pgc_watermark=1&action=uploadimage&encode=utf-8";
			HttpPost httpPost = new HttpPost(postUrl);
//			String cookies="";
//			cookies="s_v_web_id=fd7f003a2268bb0632f5be31b7122263; sso_auth_status=ab98c54b624af27362330180c74b5e10; sso_uid_tt=039dc059ac5ff19669627549cb2dcf18; sso_uid_tt_ss=039dc059ac5ff19669627549cb2dcf18; toutiao_sso_user=1a2bfee37ae434de9ce5ee8d4a171080; toutiao_sso_user_ss=1a2bfee37ae434de9ce5ee8d4a171080; passport_auth_status=8c914a1cbabb7ec59d33384011b539bf%2Cb17855cc278a7887e0c99dc1dfa89690; sid_guard=1b8b1a044c3cf8648eef036d231147f7%7C1585634459%7C5184000%7CSat%2C+30-May-2020+06%3A00%3A59+GMT; uid_tt=1428fda05b092f1d5f227fb227abb083; uid_tt_ss=1428fda05b092f1d5f227fb227abb083; sid_tt=1b8b1a044c3cf8648eef036d231147f7; sessionid=1b8b1a044c3cf8648eef036d231147f7; sessionid_ss=1b8b1a044c3cf8648eef036d231147f7; gftoken=MWI4YjFhMDQ0Y3wxNTg1NjM5NTM1MjB8fDAGBgYGBgY; SLARDAR_WEB_ID=520fffad-7a19-4190-8af7-7e4107729303";
//			httpPost.addHeader("Host", "mp.toutiao.com");
//			httpPost.addHeader("Origin", "mp.toutiao.com");
//			httpPost.addHeader("Cookie", cookies);
			// 增加header信息
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpPost.addHeader(entry.getKey(), entry.getValue());
				}
			}
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			File f= new File(filePath);
			String filename = f.getName();

			if (filename.indexOf(".") < 0) {
				filename = filename.concat(".png");
			}
			log.info("uploadLocalImgFile():contenttype=" + ContentType.APPLICATION_OCTET_STREAM);
			log.info("uploadLocalImgFile():name=" + filename);
			String name="file";
			if(paraData.containsKey("name"))
			{
				name=paraData.getString("name");
			}

			multipartEntityBuilder.addBinaryBody(name, new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM,
					filename);

			httpPost.setEntity(multipartEntityBuilder.build());

			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity rentity = response.getEntity();

			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				String entityStr = EntityUtils.toString(rentity, Consts.UTF_8);
				log.info("uploadLocalImgFile():entityStr = " + entityStr);

				JSONObject entityjson = JSONObject.parseObject(entityStr);
				System.out.println(entityjson.toString());

				if (entityjson.containsKey("errcode")) {
					//entityjson.replace("errmsg", WeiXinError.getDesc(entityjson.getString("errcode")));
				}

				return entityjson;
			}


		} catch (Exception e) {
			log.error("uploadLocalImgFile():上传图文消息内的图片获取URL时发生异常", e);
		}
		return null;
	}

	/**
	 * post上传，功能强大
	 */
	public static JSONObject uploadStream(JSONObject paraData ,Map<String, String> headers ) {
		JSONObject result = new JSONObject();
		//创建连接
		HttpURLConnection connection ;
		StringBuffer sbuffer=null;
		String reqUrl=!paraData.containsKey("url") ? "" : paraData.getString("url");
		//PUT
		String method=!paraData.containsKey("method") ? "POST" : paraData.getString("method");
		String charsetName=!paraData.containsKey("charsetName") ? "utf-8" : paraData.getString("charsetName");
		int readTimeout=!paraData.containsKey("readTimeout") ? 10000 : paraData.getInteger("readTimeout");
		int connectTimeout=!paraData.containsKey("connectTimeout") ? 10000 : paraData.getInteger("connectTimeout");
		boolean doOutput=!paraData.containsKey("doOutput") ? true : paraData.getBooleanValue("doOutput");
		boolean doInput=!paraData.containsKey("doInput") ? true : paraData.getBooleanValue("doInput");
		byte[] stream=!paraData.containsKey("stream") ? null : paraData.getBytes("stream");
		String content="";
		if(stream==null)
		{
			content=!paraData.containsKey("content") ? "" : paraData.getString("content");
			stream=new String(content).getBytes();
		}
		try {
			URL url = new URL(reqUrl);
			//添加 请求内容
			connection= (HttpURLConnection) url.openConnection();
			//设置http连接属性
			connection.setDoOutput(doOutput);// http正文内，因此需要设为true, 默认情况下是false;
			connection.setDoInput(doInput);// 设置是否从httpUrlConnection读入，默认情况下是true;
			connection.setRequestMethod(method); // 可以根据需要 提交 GET、POST、DELETE、PUT等http提供的功能
			//connection.setUseCaches(false);//设置缓存，注意设置请求方法为post不能用缓存
			// connection.setInstanceFollowRedirects(true);
			// 增加header信息
			System.out.println("url----"+"----"+reqUrl);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.addRequestProperty(entry.getKey(), entry.getValue());//设定 请求格式 json，也可以设定xml格式的
					//  System.out.println(entry.getKey()+"----"+entry.getValue());
				}
			}
			connection.setReadTimeout(readTimeout);//设置读取超时时间
			connection.setConnectTimeout(connectTimeout);//设置连接超时时间
			connection.connect();
			OutputStream out = connection.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中
			out.write(stream);            //out.write(new String("测试数据").getBytes());
			out.flush();
			// 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中
			out.close();

			//读取响应
			if (connection.getResponseCode()==200)
			{
				// 从服务器获得一个输入流
				InputStreamReader inputStream =new InputStreamReader(connection.getInputStream());//调用HttpURLConnection连接对象的getInputStream()函数, 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
				BufferedReader reader = new BufferedReader(inputStream);
				String lines;
				sbuffer= new StringBuffer("");
				while ((lines = reader.readLine()) != null) {
					lines = new String(lines.getBytes(), charsetName);
					sbuffer.append(lines);
					//System.out.println(lines);
				}

				JSONObject entityjson = JSONObject.parseObject(sbuffer.toString());
				System.out.println(entityjson.toString());
				reader.close();
				result.put("respCode", "0");
				result.put("respDesc", "ok");
				result.put("result", entityjson);
			}
			else{
				System.out.println("uploadStream 请求失败"+connection.getResponseCode()+"----"+ connection.getResponseMessage());
				result.put("respCode", "-1");
				result.put("respDesc", "uploadStream 请求失败"+connection.getResponseCode()+"----"+ connection.getResponseMessage());
			}
			//断开连接
			connection.disconnect();
		}
		catch (IOException e) {
			e.printStackTrace();
			result.put("respCode", "-1");
			result.put("respDesc", "uploadStream 请求失败");
		}
		return result;
	}

	/**
	 * 表单形式文件上传
	 */
	public static JSONObject uploadStream(JSONObject paraData ,Map<String, String> headers,Map<String, String> textMap,Map<String, String> fileMap,String fileType) {
		JSONObject result = new JSONObject();
		//创建连接
		HttpURLConnection connection ;
		StringBuffer sbuffer=null;
		String reqUrl=!paraData.containsKey("url") ? "" : paraData.getString("url");
		//PUT
		String method=!paraData.containsKey("method") ? "POST" : paraData.getString("method");
		String charsetName=!paraData.containsKey("charsetName") ? "utf-8" : paraData.getString("charsetName");
		int readTimeout=!paraData.containsKey("readTimeout") ? 10000 : paraData.getInteger("readTimeout");
		int connectTimeout=!paraData.containsKey("connectTimeout") ? 10000 : paraData.getInteger("connectTimeout");
		boolean doOutput=!paraData.containsKey("doOutput") ? true : paraData.getBooleanValue("doOutput");
		boolean doInput=!paraData.containsKey("doInput") ? true : paraData.getBooleanValue("doInput");

		String BOUNDARY = "----WebKitFormBoundarycUuTHUBO8uRIJcrK";
		try {
			URL url = new URL(reqUrl);
			//添加 请求内容
			connection= (HttpURLConnection) url.openConnection();
			//设置http连接属性
			connection.setDoOutput(doOutput);// http正文内，因此需要设为true, 默认情况下是false;
			connection.setDoInput(doInput);// 设置是否从httpUrlConnection读入，默认情况下是true;
			connection.setRequestMethod(method); // 可以根据需要 提交 GET、POST、DELETE、PUT等http提供的功能
			//connection.setUseCaches(false);//设置缓存，注意设置请求方法为post不能用缓存
			// connection.setInstanceFollowRedirects(true);
			// 增加header信息
			System.out.println("url----"+"----"+reqUrl);
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.addRequestProperty(entry.getKey(), entry.getValue());//设定 请求格式 json，也可以设定xml格式的
					//  System.out.println(entry.getKey()+"----"+entry.getValue());
				}
			}
			connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

			connection.setReadTimeout(readTimeout);//设置读取超时时间
			connection.setConnectTimeout(connectTimeout);//设置连接超时时间
			connection.connect();
			OutputStream out = connection.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中


			StringBuffer textBuf = new StringBuffer();
			if (textMap != null)
			{

				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext())
				{
					Map.Entry entry = (Map.Entry) iter.next();
					String name=(String) entry.getKey();
					String value=(String) entry.getValue();
					if (value == null) {
						continue;
					}
					textBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					textBuf.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
					textBuf.append(value);

				}
				out.write(textBuf.toString().getBytes());
			}
			if (fileMap != null)
			{
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext())
				{
					Map.Entry entry = (Map.Entry) iter.next();
					String name=(String) entry.getKey();
					String value=(String) entry.getValue();
					if (value == null) {
						continue;
					}
					File file = new File(value);
					String filename = file.getName();
					//没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
					fileType = new MimetypesFileTypeMap().getContentType(file);
					//contentType非空采用filename匹配默认的图片类型
					if(!"".equals(fileType)){
						if (filename.endsWith(".png")) {
							fileType = "image/png";
						}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
							fileType = "image/jpeg";
						}else if (filename.endsWith(".gif")) {
							fileType = "image/gif";
						}else if (filename.endsWith(".ico")) {
							fileType = "image/image/x-icon";
						}
					}
					if (fileType == null || "".equals(fileType)) {
						fileType = "application/octet-stream";
					}
					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + value + "\"\r\n");
					strBuf.append("Content-Type:" + fileType + "\r\n\r\n");
					out.write(strBuf.toString().getBytes());
					DataInputStream in = new DataInputStream(new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}

			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			// 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中
			out.close();

			//读取响应
			if (connection.getResponseCode()==200)
			{
				// 从服务器获得一个输入流
				InputStreamReader inputStream =new InputStreamReader(connection.getInputStream());//调用HttpURLConnection连接对象的getInputStream()函数, 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
				BufferedReader reader = new BufferedReader(inputStream);
				String lines;
				sbuffer= new StringBuffer("");
				while ((lines = reader.readLine()) != null) {
					lines = new String(lines.getBytes(), charsetName);
					sbuffer.append(lines);
					//System.out.println(lines);
				}

				JSONObject entityjson = JSONObject.parseObject(sbuffer.toString());
				System.out.println(entityjson.toString());
				reader.close();
				result.put("respCode", "0");
				result.put("respDesc", "ok");
				result.put("result", entityjson);
			}
			else{
				System.out.println("uploadStream 请求失败"+connection.getResponseCode()+"----"+ connection.getResponseMessage());
				result.put("respCode", "-1");
				result.put("respDesc", "uploadStream 请求失败"+connection.getResponseCode()+"----"+ connection.getResponseMessage());
			}
			//断开连接
			connection.disconnect();
		}
		catch (IOException e) {
			e.printStackTrace();
			result.put("respCode", "-1");
			result.put("respDesc", "uploadStream 请求失败");
		}
		return result;
	}


	/**
	 * 清除有影响的标签  如javascript
	 *
	 * */
	public static String HtmlLableClear(String htmlCont)
	{
		String ret="";
		try
		{
			String body = "";
			Matcher bodyContent = java.util.regex.Pattern.compile("<[\\s]*?body[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?body[\\s]*?>", Pattern.CASE_INSENSITIVE).matcher(htmlCont);
			if(bodyContent.find()){
				body = bodyContent.group();
				body = body.substring(body.indexOf(">")+1,body.lastIndexOf("<"));
			}
			ret = java.util.regex.Pattern.compile("<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>", Pattern.CASE_INSENSITIVE).matcher(body).replaceAll("");
			ret = java.util.regex.Pattern.compile("<!-[\\s\\S]*?->",Pattern.CASE_INSENSITIVE).matcher(ret).replaceAll("");
			ret = java.util.regex.Pattern.compile("<\\s*style\\s*[^>]*?\\s*>\\s*[\\s\\S]*?\\s*<\\s*/\\s*style\\s*?>",Pattern.CASE_INSENSITIVE).matcher(ret).replaceAll("");
			ret = java.util.regex.Pattern.compile("<\\s*link\\s.*?href\\s*=\\s*[^>]*\\s*/?\\s*>",Pattern.CASE_INSENSITIVE).matcher(ret).replaceAll("");
			ret = java.util.regex.Pattern.compile("<[\\s]*?iframe[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?iframe[\\s]*?>",Pattern.CASE_INSENSITIVE).matcher(ret).replaceAll("");

		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}





	/**
	 * 根据html源码 获取imglist
	 *
	 * */
	public static List<String> getHtmlImgUrl(String htmlCont)
	{
		List<String> imgs = new ArrayList<>();
		Matcher imgContents = java.util.regex.Pattern.compile("<\\s*img\\s*([^>]*)\\s*/?\\s*>", Pattern.CASE_INSENSITIVE).matcher(htmlCont);
		while(imgContents.find()){
			String img = imgContents.group();
			Matcher imgSrc = java.util.regex.Pattern.compile("src=['\"][\\s\\S]*?['\"]", Pattern.CASE_INSENSITIVE).matcher(img);
			while(imgSrc.find()){
				String src = imgSrc.group();
				if(src.indexOf("'")>0){
					imgs.add(src.substring(src.indexOf("'")+1,src.lastIndexOf("'")));
				}else if(src.indexOf("\"")>0){
					imgs.add(src.substring(src.indexOf("\"")+1,src.lastIndexOf("\"")));
				}
			}
		}

		return imgs;
	}


	/**
	 * 根据html源码获取videolist
	 *
	 * */
	public static Map<String,String> getHtmlVideoUrl(String htmlCont)
	{
		Map<String,String> map = new HashMap<>();
		Matcher vContents = java.util.regex.Pattern.compile("<\\s*video\\s*([^>]*)\\s*/?\\s*>", Pattern.CASE_INSENSITIVE).matcher(htmlCont);
		while(vContents.find()){
			String video = vContents.group();
			Matcher vSrc = java.util.regex.Pattern.compile("src=['\"][\\s\\S]*?['\"]", Pattern.CASE_INSENSITIVE).matcher(video);
			while(vSrc.find()){
				String src = vSrc.group();
				if(src.indexOf("'")>0){
					src = src.substring(src.indexOf("'")+1,src.lastIndexOf("'"));
					map.put(src, video);
				}else if(src.indexOf("\"")>0){
					src = src.substring(src.indexOf("\"")+1,src.lastIndexOf("\""));
					map.put(src, video);
				}
			}
		}

		return map;
	}



	/**
	 * 替换图片
	 * @param htmlCont
	 * @param imgArray
	 * @return
	 */
	public static String replaceHtmlImgUrl(String htmlCont,JSONObject imgArray)
	{
		String result = htmlCont;
		if(imgArray.keySet().size()>0){
			for(String old:imgArray.keySet()){
				result = result.replace(old, imgArray.getString(old));
			}
		}
		return result;
	}

	/**
	 * 简单正则匹配
	 * String str="_ga=GA1.2.1597872624.1590045728; s_v_web_id=kaq2as4x_RLPMl0jT_1l1a_4X1d_9HvK_vcKCJ2t0B7Wo; csrf_token=qhftNNBGwTBvGXPgyOBEdCONOxkVssNS; ttwid=6831691329191216653; passport_csrf_token=3ac412f320eca2712647757c32f6c35c; odin_tt=4ac235c96752cb8fae57ea668710a8df132d308c1287d2841525d0f83458e3cbe3aabc58c9be4a039ce7700e46f8b9f3; sso_uid_tt=3259b030a0aa00a8649760384f5524e4; sso_uid_tt_ss=3259b030a0aa00a8649760384f5524e4; toutiao_sso_user=f6fb185d7ca2a25b38f59b9ce346802d; toutiao_sso_user_ss=f6fb185d7ca2a25b38f59b9ce346802d; passport_auth_status=a5f6e438aef0479cf4cf279c0fe081a2%2C; sid_guard=7c6d4822db1050e11402358d5ab35e14%7C1590627561%7C5184000%7CMon%2C+27-Jul-2020+00%3A59%3A21+GMT; uid_tt=16e5817e4913663e0b87b6fe83452aee; uid_tt_ss=16e5817e4913663e0b87b6fe83452aee; sid_tt=7c6d4822db1050e11402358d5ab35e14; sessionid=7c6d4822db1050e11402358d5ab35e14; sessionid_ss=7c6d4822db1050e11402358d5ab35e14; oc_login_type=LOGIN_PERSON; SLARDAR_WEB_ID=9229c99a-f302-45cf-ba15-e1563b4d2462";
	 * String pattern = "csrf_token=(.*?);";
	 * @param str
	 * @param pattern
	 * @return
	 */
	public static String easyMatch(String str,String pattern)
	{
		String result = "";
		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);

		// 现在创建 matcher 对象
		Matcher m = r.matcher(str);
		if (m.find( )) {
			result= m.group(1);
		}
		return result;
	}


	/**
	 * @param js  JS文件路径
	 * @param func	调用方法名
	 * @param params	所需参数
	 * @return	调用JS文件 (全局方法)
	 */
	public static Object invokeJS(String js,String func,Object[] params){
		Object res = null;
		try{
			ScriptEngineManager mgr = new ScriptEngineManager();
			ScriptEngine engine = mgr.getEngineByName("javascript");
			engine.eval(readJSFile(js));
			Invocable inv = (Invocable) engine;
			res = (params==null||params.length==0)?inv.invokeFunction(func):(Object)inv.invokeFunction(func,params);
		}catch(Exception e){
			e.printStackTrace();
		}
		return res;
	}


	/**
	 * @param js  JS文件路径	obj 内部对象名
	 * @param func	调用方法名
	 * @param params	所需参数
	 * @return	调用JS文件	(内部对象方法)
	 */
	public static Object invokeJS(String js,String obj,String func,Object[] params){
		Object res = null;
		try{
			ScriptEngineManager mgr = new ScriptEngineManager();
			ScriptEngine engine = mgr.getEngineByName("javascript");
			engine.eval(readJSFile(js));
			Object item = engine.get(obj);
			Invocable inv = (Invocable) engine;
			res = (params==null||params.length==0)?inv.invokeMethod(item,func):(Object)inv.invokeMethod(item,func,params);
		}catch(Exception e){
			e.printStackTrace();
		}
		return res;
	}


	private static String readJSFile(String js)  {
		StringBuffer script = new StringBuffer();
		File file = new File(js);
		FileReader filereader;
		try {
			filereader = new FileReader(file);
			BufferedReader bufferreader = new BufferedReader(filereader);
			String tempString = null;
			while ((tempString = bufferreader.readLine()) != null) {
				script.append(tempString).append("\n");
			}
			bufferreader.close();
			filereader.close();
			System.out.println("js:"+script.toString());
		}

		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return script.toString();
	}

	/**
	 * @return	根据流获取扩展名
	 */
	public static String getExtByStream(InputStream is){
		String ext = "";
		byte[] b = new byte[3];
		try{
			is.read(b, 0, b.length);
			if(b!=null&&b.length>0){
				String header = "";
				StringBuilder sb = new StringBuilder();
				for(int i=0;i<b.length;i++){
					int v= b[i] & 0xFF;
					String hv = Integer.toHexString(v);
					if(hv.length()<2){
						sb.append(0);
					}
					sb.append(hv);
				}
				header =sb.toString().toUpperCase().substring(0,6);
				switch(header){
					case "FFD8FF": ext = "jpg"; break;
					case "89504E": ext = "png"; break;
					case "474946": ext = "gif"; break;
					case "49492A": ext = "tif"; break;
					case "424D": ext = "bmp"; break;
					case "414331": ext = "dwg"; break;
					case "384250": ext = "psd"; break;
					case "7B5C72": ext = "rtf"; break;
					case "3C3F78": ext = "xml"; break;
					case "3C2144": ext = "html"; break;
					case "44656C": ext = "eml"; break;
					case "CFAD12": ext = "dbx"; break;
					case "214244": ext = "pst"; break;
					case "D0CF11": ext = "xls"; break;
					case "537461": ext = "mdb"; break;
					case "FF5750": ext = "wpd"; break;
					case "252150": ext = "eps"; break;
					case "255044": ext = "pdf"; break;
					case "AC9EBD": ext = "qdf"; break;
					case "E38285": ext = "pwl"; break;
					case "504B03": ext = "zip"; break;
					case "526172": ext = "rar"; break;
					case "574156": ext = "wav"; break;
					case "415649": ext = "avi"; break;
					case "2E7261": ext = "ram"; break;
					case "2E524D": ext = "rm"; break;
					case "000001": ext = "mpg"; break;
					case "6D6F6F": ext = "mov"; break;
					case "3026B2": ext = "asf"; break;
					case "4D5468": ext = "mid"; break;
					default: break;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return ext;
	}


	/**
	      * 获取文件大小
	      * 
	      * @param size
	      * @return
	      */
	public static String getPrintSize(long size) {
		// 如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
		if (size < 1024) {
			return String.valueOf(size) + "B";
		} else {
			size = size / 1024;
		}
		// 如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
		// 因为还没有到达要使用另一个单位的时候
		// 接下去以此类推
		if (size < 1024) {
			return String.valueOf(size) + "KB";
		} else {
			size = size / 1024;
		}
		if (size < 1024) {
			// 因为如果以MB为单位的话，要保留最后1位小数，
			// 因此，把此数乘以100之后再取余
			size = size * 100;
			return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB";
		} else {
			// 否则如果要以GB为单位的，先除于1024再作同样的处理
			size = size * 100 / 1024;
			return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
		}
	}


	public static JSONArray getFiles(String curPath ){


		JSONArray jsonArray = new JSONArray();
		try
		{
			File file = new File(curPath);
			File [] files = file.listFiles();
			for(File f:files)
			{
				JSONObject json = new JSONObject();
				json.put("id", f.getPath());
				json.put("path", f.getPath());
				json.put("parentId", curPath);
				json.put("parent", f.getParent());
				json.put("name", f.getName());
				json.put("size",  getPrintSize(f.length()));
				Long lastModified = file.lastModified();
				Date date = new Date(lastModified);
				json.put("updateTime",  ToolsUtil.utilDateToDateStr(date, "yyyy-MM-dd HH:mm:ss"));

				//System.out.println(f.getParent());
				if(f.isDirectory())
				{
					json.put("hasChild", true);
					json.put("type",  "");
					//System.out.println("directory path="+f.getPath()+"; name="+f.getName());
				}
				else
				{
					json.put("hasChild", false);
					System.out.println(f.getPath()+"----"+CheckFileFormatUtil.getFileType(f.getPath()));
					json.put("type",  CheckFileFormatUtil.getFileType(f.getPath()));
					// System.out.println("file path="+f.getPath()+"; name="+f.getName());
				}

				jsonArray.add(json);
			}
		}
		catch(Exception e)
		{
			jsonArray=null;
		}
		return jsonArray;

	}

	public static Map<String,String[]> covertData(JSONArray jsarry) {
		Map<String,String[]> map = new HashMap<String,String[]>();
		try {
			//JSONArray jsarry = json.getJSONArray("detaillist");

			for (Iterator iterator = jsarry.iterator(); iterator.hasNext();) {
				JSONObject job = (JSONObject) iterator.next();
				Iterator<String> it = job.keySet().iterator();
				while (it.hasNext()) {
					String key = it.next();
					String value = job.getString(key);
					if (map.containsKey(key)) {
						String[] ss=map.get(key);
						ss=addElement(ss,value);
						map.put(key, ss);
					} else {
						String[] ss={value};
						map.put(key, ss);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return map;
	}


	public static String[] addElement(String[] original, String element) {
		int length = original.length;
		String[] destination = new String[length + 1];
		System.arraycopy(original, 0, destination, 0, length);
		destination[length] = element;
		return destination;
	}

	public static String[] getMapValueForKey(Map<String,String[]> map, String key) {
		String[] ress=new String[]{};
		for (Map.Entry<String, String[]> m : map.entrySet()) {
			if(key.equals(m.getKey())){
				ress= m.getValue();
				break;
			}
		}
		return ress;
	}

	public static String getTimeInMillis() {
		Calendar c = Calendar.getInstance();
		String str = String.valueOf(c.getTimeInMillis());
		c = null;
		return str;
	}


	public static String msgHandler(String msg,int maxLength){
		String result = "";
		if (StringUtils.isEmpty(msg)) {
			return result;
		}
		result = msg;
		if (msg.length() > maxLength) {
			result = msg.substring(0, maxLength);
		}
		return result;
	}

	public static java.util.Date strToDateTime(String str)
	{
		try
		{
			if(str == null || "".equals(str))
			{
				return null;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.parse(str);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}

	}

	public static String postUrl(String url, String contents) {
		InputStream ins=null;
		InputStreamReader inr=null;
		BufferedReader bfr=null;
		HttpURLConnection conn =null;
		String result = null;
		try {
			System.out.println("post>>>" + url);
			URL serverUrl = new URL(url);
			conn = (HttpURLConnection) serverUrl
					.openConnection();
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);
			conn.setRequestMethod("POST");// "POST" ,"GET"
			conn.addRequestProperty("Referer", url);
			conn.setRequestProperty("Accept", "*/*");
			// System.out.println("cookie:"+"");
			conn.addRequestProperty("Cookie", "");
			conn.addRequestProperty("Content-Language", "en");
			conn.addRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.setDoOutput(true);
			conn.connect();
			conn.getOutputStream().write(contents.getBytes("utf-8"));
			String cookie = "";
			if (conn.getHeaderFields().get("Set-Cookie") != null) {
				for (String s : conn.getHeaderFields().get("Set-Cookie")) {
					cookie += s;
				}
			}

			// System.out.println("获取cookie：\n"+cookie);

			ins = conn.getInputStream();
			String charset = "utf-8";
			inr = new InputStreamReader(ins, charset);
			bfr = new BufferedReader(inr);
			String line = "";
			StringBuffer res = new StringBuffer();
			do {
				if (!"".equals(line)) {
					res.append(line + "\n");
				}
				line = bfr.readLine();
			} while (line != null);
			// System.out.print(">>>===\n"+res);
			result=(res.toString()).trim();;

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("[POST请求]向地址：" + url + " 发送数据：" + contents + " 发生错误! ");

		}
		finally {// 使用finally块来关闭输出流、输入流
			try {
				if (bfr != null) {
					//System.out.println("bfr关闭正常");
					bfr.close();
				}
				if (inr != null) {
					//	System.out.println("inr关闭正常");
					inr.close();
				}
				if (ins != null) {
					//	System.out.println("ins关闭正常");
					ins.close();
				}
				if (conn != null) {
					//	System.out.println("conn关闭正常");
					conn.disconnect();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				System.out.println("关闭流异常");
			}
		}
		return result;
	}


	public static JSONObject parseJson(String path){
		JSONObject jso = null;
		try{
			File jsonFile = new File(path);
			if(jsonFile.exists()&&jsonFile.isFile()){
				FileReader fileReader = new FileReader(jsonFile);
				Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
				int ch = 0;
				StringBuffer sb = new StringBuffer();
				while ((ch = reader.read()) != -1) {
					sb.append((char) ch);
				}
				fileReader.close();
				reader.close();
				jso = JSON.parseObject(sb.toString());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return jso;
	}



	public static String postForm(String url,JSONObject params){
		String result = null;
		try{
			PostMethod post = new PostMethod(url);
			post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			NameValuePair[] data = new NameValuePair[params.size()];
			int idx = 0;
			for(String key:params.keySet()){
				data[idx] = new NameValuePair(key,params.getString(key));
				idx++;
			}
			post.setRequestBody(data);
			HttpClient httpClient = new HttpClient();
			httpClient.executeMethod(post);
			result = post.getResponseBodyAsString();

		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public static String[] randNum(int min,int max,int num){
		String[] result = new String[num];
		Set<String> nums = new HashSet<>();
		Random rand = new Random();
		while(nums.size()<num){
			nums.add(rand.nextInt(max-min+1)+min+"");
		}
		return nums.toArray(result);
	}

	public static long randNum(long min,long max){
		return (long)(Math.random() * (max - min + 1) + min);
	}

	public static String arrToStr (String[] ary){
		StringBuffer sb = new StringBuffer();
		sb. append(",");
		for(int i = 0; i < ary.length; i++){
			sb. append(ary[i].trim()+",");

		}
		String newStr = sb.toString();
		return newStr;
	}




	public static void fileChannelCopy(File s, File t) {
		try {
			InputStream in =null;
			OutputStream out =null;
			try {
				in =new BufferedInputStream(new FileInputStream(s),1024);
				out =new BufferedOutputStream(new FileOutputStream(t),1024);
				byte[] buffer =new byte[1024];
				int len;
				while ((len=in.read(buffer))!=-1) {
					out.write(buffer,0,len);
				}
			}finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}






	public static File createNewFile(HttpServletRequest request,String fromDir,String fromfileName,String SaveDir,String SavefileName ){
		//读取模板，并赋值到新文件************************************************************
		//文件模板路径
		//String path =request.getRealPath(SystemConfig.FILETEMPLATE);
		//String fileName="purchaseContract.xls";
		//File file=new File(path+"/"+fileName);
		String path =request.getRealPath(fromDir);
		File file=new File(path+"/"+fromfileName+".xls");


		//保存文件的路径
//        String realPath = request.getRealPath(SystemConfig.UPLOAD_FILE_DIR);
		String realPath = request.getRealPath(SaveDir);
		//新的文件名
//        String newFileName ="采购合同"+System.currentTimeMillis() +".xls";
		String newFileName =SavefileName+System.currentTimeMillis() +".xls";
		//判断路径是否存在
		File dir =new File(realPath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		//写入到新的excel
		File newFile =new File(realPath, newFileName);
		try {
			newFile.createNewFile();
			//复制模板到新文件
			fileChannelCopy(file, newFile);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return newFile;
	}

	public static JSONArray getAllFiles(String dirPath, String _type) {

		JSONArray array = new JSONArray();
		return getAllFiles(dirPath,_type,array);
	}


	private static void delFile(File file) {

		if (file.exists()) {
			file.delete();
		}

	}

	public static JSONArray getAllFiles(String dirPath, String _type,
										JSONArray array) {
		File f = new File(dirPath);
		if (!f.exists()) {// 判断路径是否存在
			return null;
		}

		File[] files = f.listFiles();

		if (files == null) {// 判断权限
			return null;
		}

		for (File _file : files) {// 遍历目录
			if (_file.isFile()) {
				String filePath = _file.getAbsolutePath();
				if (_type == null) {
					String fileName ="";
					fileName = _file.getName();
//					fileName = _file.getName().substring(0,
//							fileName.length() - 4);// 获取文件名
					filePath = _file.getAbsolutePath();// 获取文件路径
					// Log.d("LOGCAT","fileName:"+fileName);
					// Log.d("LOGCAT","filePath:"+filePath);
					try {
						JSONObject _fInfo = new JSONObject();
						_fInfo.put("name", fileName);
						_fInfo.put("path", filePath);
						array.add(_fInfo);
					} catch (Exception e) {
						e.printStackTrace();
					}
					delFile(_file);
				} else {
					if (_file.getName().endsWith(_type))
					{
						filePath = _file.getAbsolutePath();// 获取文件路径
						String fileName = _file.getName();
						// Log.d("LOGCAT","fileName:"+fileName);
						// Log.d("LOGCAT","filePath:"+filePath);
						try {
							JSONObject _fInfo = new JSONObject();
							_fInfo.put("name", fileName);
							_fInfo.put("path", filePath);
							array.add(_fInfo);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					delFile(_file);
				}
			} else if (_file.isDirectory()) {// 查询子目录
				// System.out.println(_file.getName());
				array = getAllFiles(_file.getAbsolutePath(), _type, array);
			} else {


			}
		}
		return array;
	}


	public static void main(String[] args)
	{

		JSONArray files=getAllFiles("D:\\log",null);
		System.out.println(files.toJSONString());
//		System.out.println(Arrays.toString(randNum(1,100,20)));
//	    String str=arrToStr(randNum(1,100,10));
//		System.out.println(str.substring(1, str.length()-1));

	}

//	public static void mainEx(String[] args) {
//		String tableSql="SELECT dept_name AS NAME,dept_id AS id, dept_parent_id AS pid FROM dept  WHERE dept_sts='A' ";
//		//tableSql="SELECT menu_name NAME, menu_id id, menu_superior pid FROM menu WHERE is_display='Y' ";
//		System.out.println(nestSql("NAME,id,pid,levels,paths",tableSql,"1",true));
//        Object obj=  invokeJS("D://apache-tomcat-7.0.82/webapps/ssm/plugin/js/signature.js", "dycs", "sign", new String[]{"695016118"});
//		System.out.println(obj);
//	}
}

